﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;

using EntitySpaces.Interfaces;
using yncTech.BusinessObjects;
using yncTech.Common;

public partial class Admin_FinLend_FinLend001 : AdminBasePage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            txtStartDate.Value = DateTime.Now.AddMonths(-1).Date.ToString(ConstantValue.DateFormat);
            txtEndate.Value = DateTime.Now.ToString(ConstantValue.DateFormat);
            if (Session["sd"] != null)
            {
                txtStartDate.Value = Session["sd"].ToString();
            }
            if (Session["ed"] != null)
            {
                txtEndate.Value = Session["ed"].ToString();
            }
            if (Session["drpLeader"] != null)
            {
                drpLeader.SelectedValue = Session["drpLeader"].ToString();
            }
            if (Session["drpLoanee"] != null)
            {
                drpLoanee.SelectedValue = Session["drpLoanee"].ToString();
            }
            if (Session["drpLendType"] != null)
            {
                drpLendType.SelectedValue = Session["drpLendType"].ToString();
            }
        }

    }

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        Session["sd"] = txtStartDate.Value;
        Session["ed"] = txtEndate.Value;
        Session["drpLeader"] = drpLeader.SelectedValue;
        Session["drpLoanee"] = drpLoanee.SelectedValue;
        Session["drpLendType"] = drpLendType.SelectedValue;
    }


    protected void PageChanged(object sender, DataGridPageChangedEventArgs e)
    {
        FinLendQuery q1 = new FinLendQuery("q1");
        TSCodeTableQuery q2 = new TSCodeTableQuery("q2");
        TSCodeTableQuery q3 = new TSCodeTableQuery("q3");
        BFThirdUnitQuery q4 = new BFThirdUnitQuery("q4");

        ArrayList args = new ArrayList();
        args.Add(q1.CreatedBy == LoginUserInfo.CurrentUser.LoginName);

        if (!string.IsNullOrEmpty(txtStartDate.Value))
        {
            args.Add(q1.CreatedDttm >= txtStartDate.Value);
        }
        if (!string.IsNullOrEmpty(txtEndate.Value))
        {
            args.Add(q1.CreatedDttm <= DateTime.Parse(txtEndate.Value).AddDays(1));
        }
        if (!string.IsNullOrEmpty(drpLeader.SelectedValue))
        {
            args.Add(q1.Leader == drpLeader.SelectedValue);
        }
        if (!string.IsNullOrEmpty(drpLoanee.SelectedValue))
        {
            args.Add(q1.Loanee == drpLoanee.SelectedValue);
        }
        if (!string.IsNullOrEmpty(drpLendType.SelectedValue))
        {
            args.Add(q1.LendType == drpLendType.SelectedValue);
        }

        q1.Select(q1, q2.Value1.As("LendTypeName"), q3.Value1.As("LendStatusName"), q4.Name.As("ThirdUnitName")).Where(args.ToArray());
        q1.InnerJoin(q2).On(q1.LendType == q2.Code);
        q1.InnerJoin(q3).On(q1.LendStatus == q3.Code);
        q1.InnerJoin(q4).On(q1.ThirdUnitID == q4.ThirdUnitID);
        q1.OrderBy(q1.CreatedDttm.Descending);

        pageGrid.DataSource = q1.LoadDataTable();
        pageGrid.CurrentPage = e.NewPageIndex;
        pageGrid.DataBind();
    }

    protected override void OnUnload(EventArgs e)
    {
        base.OnUnload(e);
        Session.Remove("sd");
        Session.Remove("ed");
        Session.Remove("drpLeader");
        Session.Remove("drpLoanee");
        Session.Remove("drpLendType");

    }

    #region  Delete_Command
    protected void Delete_Command(object sender, CommandEventArgs e)
    {
        decimal Id = decimal.Parse(e.CommandArgument.ToString());
        using (esTransactionScope tr = new esTransactionScope())
        {
            FinLendReceiptCollection finLendReceiptCollection = new FinLendReceiptCollection();
            finLendReceiptCollection.Query.Where(finLendReceiptCollection.Query.LendID == Id);
            finLendReceiptCollection.Query.Load();
            finLendReceiptCollection.MarkAllAsDeleted();
            finLendReceiptCollection.Save();

            FinReceiptCollection finReceiptCollection = new FinReceiptCollection();
            finReceiptCollection.Query.Where(finReceiptCollection.Query.LendId==Id);
            finReceiptCollection.Query.Load();
            foreach (FinReceipt fin in finReceiptCollection)
            {
                fin.LendId = null;
            }
            finReceiptCollection.Save();


            FinLend finLend = new FinLend();
            finLend.LoadByPrimaryKey(Id);
            if (finLend.es.HasData)
            {
                finLend.LendStatus = "LendStatus000";
                finLend.Save();
                ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "showMsg()", true);
            }
            tr.Complete();
        }

    }
    #endregion

    #region  Submit_Command
    protected void Submit_Command(object sender, CommandEventArgs e)
    {
        decimal Id = decimal.Parse(e.CommandArgument.ToString());
        using (esTransactionScope tr = new esTransactionScope())
        {
            FinLendReceiptCollection finLendReceiptCollection = new FinLendReceiptCollection();
            finLendReceiptCollection.Query.Where(finLendReceiptCollection.Query.LendID==Id);
            finLendReceiptCollection.Query.Load();

            if (finLendReceiptCollection.Count == 0)
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "showNews('借阅凭证数量为0，不能提交审核！');", true);
            }
            else
            {
                FinReceipt finReceipt=new FinReceipt();
                finReceipt.LoadByPrimaryKey(finLendReceiptCollection[0].ReceiptID.Value);

                FinLend finLend = new FinLend();
                finLend.LoadByPrimaryKey(Id);
                


                string contentApprove = string.Empty;
                string contentAdmin = string.Empty;
                string contentApply = string.Empty;

                string emailApprove = string.Empty;
                string emailAdmin = string.Empty;
                string emailApply = string.Empty;

                string subjectApprove = string.Empty;
                string subjectAdmin = string.Empty;
                string subjectApply = string.Empty;

                switch (finLend.LendType)
                {
                    case "LendType1"://实物内仓借阅
                        contentAdmin = @"Dear Filing Administrator,	<br />			
User has submitted a request to borrow the physical financial documents including following link from internal warehouse via system. The application is pending on approval.	<br />		
Pls support to process the request A.S.A.P once application has been approved.	<br />		
Besides, pls judge whether the inquired data is financial key data according to guideline ""Financial Key Data Inquiring"" and maintain result in the system.	<br />		
Thank you very much!";
                        contentApply = @"Dear Applicant,<br />		
Your request has already been submitted successfully. Pls follow up approval status.	<br />		
Once application has been approved, filing administrator will process your request immediately.	<br />	
	
Besides, if the data you inquired is financial key data, the additional approval need to get according to guideline ""Financial Key Data Inquiring"". Filing administrator will support	
to judge whether the inquired data is financial key data and give your feedback once they received request.	<br />		
If you have any questions, pls feel free to contact with us.	<br />		
Thank you very much!";
                        contentApprove = @"Dear Manager,	<br />		
A request has been submitted by applicant to borrow physcial financial documents from intnernal warehouse.	<br />	
Before process their request, your approval is necessary. Could you kindly go to following link to check and decide whether the pyhsical financial documents can be borrowed out 	
internal warehouse by applicant?	<br />	
If you have any questions, pls feel free to contact with us.	<br />	
Thank you very much!";
                        subjectApprove = "Approval Request: Physcial Financial Documents Inquiring from Internal Warehouse - " + finLend.Sn;
                        subjectAdmin = "Application Submit: Physcial Financial Documents Inquiring from Internal Warehouse - "+finLend.Sn;
                        subjectApply = "Application Submit: Physcial Financial Documents Inquiring from Internal Warehouse - " + finLend.Sn;
                        break;
                    case "LendType2"://实物外仓借阅
                        contentApprove = @"Dear Manager,
A request has been submitted by applicant to borrow physcial financial documents from extnernal warehouse.
Before process their request, your approval is necessary. Could you kindly go to following link to check and decide whether the pyhsical financial documents can be borrowed out 
external warehouse by applicant?
If you have any questions, pls feel free to contact with us.
Thank you very much!";
                        contentAdmin = @"Dear Filing Administrator,<br />	
User has submitted a request to borrow physical financial documents including following link from external warehouse via system. The application is pending on approval.<br />	
Pls support to process the request A.S.A.P once application has been approved.<br />	
Besides, pls judge whether the inquired data is financial key data according to guideline ""Financial Key Data Inquiring"" and maintain result in the system.<br />	
Thank you very much!";
                        contentApply = @"Dear Applicant,<br />	
Your request has already been submitted successfully. Pls follow up approval status.<br />	
Once application has been approved, filing administrator will process your request immediately.<br />	
Besides, if the data you inquired is financial key data, the additional approval need to get according to guideline ""Financial Key Data Inquiring"". Filing administrator will support
to judge whether the inquired data is financial key data and give your feedback once they received request.<br />	
If you have any questions, pls feel free to contact with us.<br />	
Thank you very much!";
                        subjectApprove = "Approval Request: Physcial Financial Documents Inquiring from External Warehouse - " + finLend.Sn;
                        subjectAdmin = "Application Submit: Physcial Financial Documents Inquiring from External Warehouse - " + finLend.Sn;
                        subjectApply = "Application Submit: Physcial Financial Documents Inquiring from External Warehouse - " + finLend.Sn;
                        break;
                    case "LendType3"://扫描件内仓借阅
                        contentAdmin = @"Dear Filing Administrator,<br />	
User has submitted a request to look up the sanned copy of corresponding financial documents including following link via system. <br />	
Pls support to process the request A.S.A.P.<br />	
Besides, pls judge whether the inquired data is financial key data according to guideline ""Financial Key Data Inquiring"" and maintain result in the system.<br />	
Thank you very much!";
                        contentApply = @"Dear Applicant,
Your request has already been submitted successfully. 
Once filing administrator received your request, they will process it immediately.
Besides, if the data you inquired is financial key data, the additional approval need to get according to guideline ""Financial Key Data Inquiring"". Filing administrator will support
to judge whether the inquired data is financial key data and give your feedback once they received request.
If you have any questions, pls feel free to contact with us.
Thank you very much!";
                        subjectAdmin = "Application Submit: Scanned Financial Documents Inquiring from Internal Warehouse - " + finLend.Sn;
                        subjectApply = "Application Submit: Scanned Financial Documents Inquiring from Internal Warehouse - " + finLend.Sn;
                        break;
                    case "LendType4"://扫描件外仓借阅
                        contentAdmin = @"Dear Filing Administrator,<br />	
User has submitted a request to look up the sanned copy of corresponding financial documents including following link from external warehouse via system. <br />	
Pls support to process the request A.S.A.P.<br />	
Besides, pls judge whether the inquired data is financial key data according to guideline ""Financial Key Data Inquiring"" and maintain result in the system.<br />	
Thank you very much!";
                        contentApply = @"Dear Applicant,<br />	
Your request has already been submitted successfully. <br />	
Once filing administrator received your request, they will process it immediately.<br />	
Besides, if the data you inquired is financial key data, the additional approval need to get according to guideline ""Financial Key Data Inquiring"". Filing administrator will support
to judge whether the inquired data is financial key data and give your feedback once they received request.<br />	
If you have any questions, pls feel free to contact with us.<br />	
Thank you very much!";
                        subjectAdmin = " Application Submit: Scanned Financial Documents Inquiring from External Warehouse - " + finLend.Sn;
                        subjectApply = "Application Submit: Scanned Financial Documents Inquiring from External Warehouse - " + finLend.Sn;
                        break;
                    case "LendType5"://现场查阅
                        contentAdmin = @"Dear Filing Administrator,<br />	
User has submitted a request to inquire physical financial documents including following link on-site at date/time (系统抓取) via system.<br />	
Pls support to process the request A.S.A.P.<br />	
Besides, pls judge whether the inquired data is financial key data according to guideline ""Financial Key Data Inquiring"" and maintain result in the system.<br />	
Thank you very much!";
                        contentApply = @"Dear Applicant,<br />	
Your request has already been submitted successfully. <br />	
Once filing administrator received your request, they will process your request immediately.<br />	
Besides, if the data you inquired is financial key data, the additional approval need to get according to guideline ""Financial Key Data Inquiring"". Filing administrator will support
to judge whether the inquired data is financial key data and give your feedback once they received request.<br />	
If you have any questions, pls feel free to contact with us.<br />	
Thank you very much!";
                        subjectAdmin = " Application Submit: Physcial Financial Documents Inquiring On-Site - " + finLend.Sn;
                        subjectApply = "Application Submit: Physcial Financial Documents Inquiring On-Site - " + finLend.Sn;
                        break;
                }


                if (finLend.es.HasData)
                {
                    switch (finLend.LendType)
                    {
                        case "LendType1"://实物内仓借阅
                            finLend.LendStatus = "LendStatus003";
                            break;
                        case "LendType2"://实物外仓借阅
                            finLend.LendStatus = "LendStatus003";
                            break;
                        case "LendType3"://扫描件内仓借阅
                            finLend.LendStatus = "LendStatus004";
                            break;
                        case "LendType4"://扫描件外仓借阅
                            finLend.LendStatus = "LendStatus004";
                            break;
                        case "LendType5"://现场查阅
                            finLend.LendStatus = "LendStatus004";
                            break;
                    }
                    
                    finLend.LendStatus = "LendStatus003";
                    finLend.ThirdUnitID = finReceipt.StorageLocation;

                    BFThirdUnit bFThirdUnit = new BFThirdUnit();
                    if (bFThirdUnit.LoadByPrimaryKey(finLend.ThirdUnitID.Value))
                    {
                        if (bFThirdUnit.ManageUserId.HasValue)
                        {
                            TSUserInfo userInfo = new TSUserInfo();
                            userInfo.LoadByPrimaryKey(bFThirdUnit.ManageUserId.Value);
                            emailAdmin = userInfo.Email;
                        }
                    }

                    TSUsersQuery q1=new TSUsersQuery("q1");
                    TSUserInfoQuery q2 = new TSUserInfoQuery("q2");
                    q1.Select(q2.Email).Where(q1.LoginName==finLend.CreatedBy);
                    q1.InnerJoin(q2).On(q1.UserID==q2.UserID);
                    emailApply = q1.LoadDataTable().Rows[0]["Email"].ToString();
                    emailApprove = finLend.ApproveEmail;

                    finLend.Save();
                }
                tr.Complete();

                SendMail.SendHtml(new string[] { emailAdmin }, subjectAdmin, contentAdmin);
                if (!string.IsNullOrEmpty(contentApprove))
                { SendMail.SendHtml(new string[] { emailApprove }, subjectApprove, contentApprove); }
                SendMail.SendHtml(new string[] { emailApply }, subjectApply, emailApply);

                ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "showNews('借阅申请已经提交！');", true);
            }
        }

        

    }
    #endregion

    #region  Cancel_Command
    protected void Cancel_Command(object sender, CommandEventArgs e)
    {
        decimal Id = decimal.Parse(e.CommandArgument.ToString());
        using (esTransactionScope tr = new esTransactionScope())
        {
            FinLend finLend = new FinLend();
            finLend.LoadByPrimaryKey(Id);
            if (finLend.es.HasData)
            {
                finLend.LendStatus = "LendStatus001";//变成新申请
                finLend.ThirdUnitID = null;
                finLend.Save();
                ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "showMsg()", true);
            }
            tr.Complete();
            ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "showNews('借阅已经撤销！');", true);
        }

        

    }
    #endregion
    
    
}